// --------------------------------------------------------------------------------------------------------------------
// <copyright file="KukaLBR4KrlCartesianPositionController.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.Robotics.Hardware.KukaLBR
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;

    using Microsoft.Robotics.Manipulation;
    using Microsoft.Robotics.Manipulation.ControllerStateMachine;
    using Microsoft.Robotics.Numerics;

    using LBR4 = Microsoft.Robotics.Hardware.KukaLBR.KukaLBR4PlusCsharpDefinitionsNativeMethods;

    /// <summary>
    /// A controller for Cartesian position of the TCP of the LBR4 relying on KRL "robot interpreter" to generation motions
    /// </summary>
    public class KukaLBR4KrlCartesianPositionController : KukaLBR4CartesianPositionController
    {
        /// <summary>
        /// Controller state machine description cache
        /// </summary>
        private static ControllerStateMachineDescription csmdCache;

        /// <summary>
        /// Determines if we have a cached copy of the controller state machine description available
        /// </summary>
        private static bool haveCachedCsmd = false;

        /// <summary>
        /// Initializes a new instance of the <see cref="KukaLBR4KrlCartesianPositionController"/> class.
        /// </summary>
        /// <param name="registerManager">Manager for assigning working registers.</param>
        /// <param name="desiredPose">Desired Cartesian pose.</param>
        /// <param name="maxLinearSpeedInMetersPerSec">The parameter is not used.</param>
        /// <param name="maxRotationalSpeedInRadPerSec">The parameter is not used.</param>
        /// <param name="timeStepInMsec">FRI cycle time.</param>
        /// <returns>A set of working registers.</returns>
        public KukaLBR4KrlCartesianPositionController(
            KukaLBR4WorkingRegisterManager registerManager,
            Pose desiredPose,
            double maxLinearSpeedInMetersPerSec,
            double maxRotationalSpeedInRadPerSec,
            double timeStepInMsec)
            : base(
                registerManager,
                desiredPose,
                maxLinearSpeedInMetersPerSec,
                maxRotationalSpeedInRadPerSec,
                timeStepInMsec)
        {
            double[] destinationFrame = HomogenousTransform.ToFrameArray(HomogenousTransform.CreateFromPose(desiredPose));

            Array.Copy(
                destinationFrame,
                this.WorkingRegisterArray.Registers[(int)LBR4.KukaLBR4PlusWorkingRegisters.CartesianPositionCommandRegister],
                this.WorkingRegisterArray.Registers[(int)LBR4.KukaLBR4PlusWorkingRegisters.CartesianPositionCommandRegister].Length);
        }

        /// <summary>
        /// Builds a state machine controller
        /// </summary>
        /// <returns>A state machine based controller</returns>
        public new ControllerStateMachineDescription BuildStateMachineDescription()
        {
            if (!haveCachedCsmd)
            {
                csmdCache = base.BuildStateMachineDescription();
                haveCachedCsmd = true;
            }

            return csmdCache;
        }

        /// <summary>
        /// Builds the controller state machine used by this controller.
        /// </summary>
        /// <returns>A controller state machine.</returns>
        protected override ControllerStateMachine BuildControllerStateMachine()
        {
            const int CartesianKrlCommandState = 0;

            ControllerStateMachine csm = new ControllerStateMachine();

            State[] stateArray = new State[1];

            stateArray[CartesianKrlCommandState] = this.BuildCartesianKrlPositionCommandState();

            csm.States = new List<State>(stateArray);
            
            return csm;
        }

        /// <summary>
        /// Build a state that simply sets the control mode to KrlCartesianImpedanceControlMode
        /// Rest of steps are taken by the KukaLBR4Controller and in a KRL script
        /// </summary>
        /// <returns>A controller state.</returns>
        protected State BuildCartesianKrlPositionCommandState()
        {
            return new State(
                (int)LBR4.ControlModes.KrlCartesianImpedanceControlMode,
                new ControllerOperation[0],
                new Transition[0],
                new Transition[0]);
        }
    }
}
